$(document).ready(function () {
    validateUser();
    getReceiptList();
    getGoodsInfo();
    checkInfo();
});

var ipAddress="localhost";
var goods;
var orderProductVOArray=new Array();


//验证用户是否登录
var validateUser=function(){
    $.ajax({
        //url: "http://" + ipAddress + ":8080/user/get_user_info",
        url: "http://" + ipAddress + ":8004/orderInfo/checkAccount",
        type: "GET",
        async: true,
        data: null,
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            if (data.message =="success") {
                //getReceiptList();
            }else{
                layer.msg("请先登录！");
                setTimeout(function(){//1秒后跳转
                    window.location.href = "./login.html"
                },1000);
            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })
};

// 获取用户的收货地址
var getReceiptList= function () {
    $.ajax({
        url: "http://" + ipAddress + ":8080/receipt/receipts",
        type: "GET",
        async: true,
        data: null,
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            console.log("size=="+data.data.length);
            if (data.message =="success") {

                    $.each(data.data, function (index, value){
                        if(index==0){
                            $("#J_addressList").append("<!-- addresslist begin -->\n" +
                                "                    <div class='address-item J_addressItem'" +
                                "                         data-address_id='11000000029891833'\n" +
                                "                         data-consignee='游宇'\n" +
                                "                         data-tel='135****0973'\n" +
                                "                         data-province_id='3'\n" +
                                "                         data-province_name='天津'\n" +
                                "                         data-city_id='37'\n" +
                                "                         data-city_name='天津市'\n" +
                                "                         data-district_id='416'\n" +
                                "                         data-district_name='滨海新区'\n" +
                                "                         data-area='416019'\n" +
                                "                         data-area_name='开发区'\n" +
                                "                         data-address='联发·第五街'\n" +
                                "                         data-tag_name=''\n" +
                                "                         data-zipcode='300457'\n" +
                                "                         data-editable='Y'\n" +
                                "                         data-neededit='N'\n" +
                                "                    onclick='confirmReceipt(this)' id='"+value.id+"' name='receipt' style='border: 1px solid red;'>\n" +
                                "                        <dl>\n" +
                                "                            <dt>\n" +
                                "                                <span class=\"tag\"></span>\n" +
                                "                                <em class=\"uname\">"+value.name+"</em>\n" +
                                "                            </dt>\n" +
                                "                            <dd class=\"utel\">\n" +
                                "                                "+value.phone+"                            </dd>\n" +
                                "                            <dd class=\"uaddress\">\n" +
                                "                                "+value.address+"\n" +
                                "                            </dd>\n" +
                                "                        </dl>\n" +
                                "                        <div class='actions' style='display:block'>\n" +
                                "                            <a onclick='updateReceipt(this)'>修改</a>\n" +
                                "                        </div>\n" +
                                "                    </div>\n" +
                                "                    <!--addresslist end -->\n"
                            );
                        }else{
                            $("#J_addressList").append("<!-- addresslist begin -->\n" +
                                "                    <div class='address-item J_addressItem'" +
                                "                         data-address_id='11000000029891833'\n" +
                                "                         data-consignee='游宇'\n" +
                                "                         data-tel='135****0973'\n" +
                                "                         data-province_id='3'\n" +
                                "                         data-province_name='天津'\n" +
                                "                         data-city_id='37'\n" +
                                "                         data-city_name='天津市'\n" +
                                "                         data-district_id='416'\n" +
                                "                         data-district_name='滨海新区'\n" +
                                "                         data-area='416019'\n" +
                                "                         data-area_name='开发区'\n" +
                                "                         data-address='联发·第五街'\n" +
                                "                         data-tag_name=''\n" +
                                "                         data-zipcode='300457'\n" +
                                "                         data-editable='Y'\n" +
                                "                         data-neededit='N'\n" +
                                "                    onclick='confirmReceipt(this)' id='"+value.id+"' name='receipt' style='border: 1px solid grey;'>\n" +
                                "                        <dl>\n" +
                                "                            <dt>\n" +
                                "                                <span class=\"tag\"></span>\n" +
                                "                                <em class=\"uname\">"+value.name+"</em>\n" +
                                "                            </dt>\n" +
                                "                            <dd class=\"utel\">\n" +
                                "                                "+value.phone+"                            </dd>\n" +
                                "                            <dd class=\"uaddress\">\n" +
                                "                                "+value.address+"\n" +
                                "                            </dd>\n" +
                                "                        </dl>\n" +
                                "                        <div class='actions' style='display:block'>\n" +
                                "                            <a onclick='updateReceipt(this)'>修改</a>\n" +
                                "                        </div>\n" +
                                "                    </div>\n" +
                                "                    <!--addresslist end -->\n"
                            );
                        }

                    });
                    $("#J_addressList").append(
                        "                    <div class=\"address-item address-item-new\" id=\"J_newAddress\" onclick='newReceipt(this)'>\n" +
                        "                        <i class=\"iconfont\">&#xe609;</i>\n" +
                        "                        <span style='color: #FF00FF'>添加新地址</span>\n" +
                        "                    </div>");

            }else{
                layer.msg("请先登录！");
                setTimeout(function(){//两秒后跳转
                    window.location.href = "./login.html"
                },1000);
            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })
};

//获取商品信息
var getGoodsInfo=function(){
    var cartIdList=new Array();
    cartIdList=getUrlParms("cartIdList").split(',');
    console.log("cartIdList==="+cartIdList);
    $.each(cartIdList, function (index, value) {
        console.log("cartId==="+value);
        //获取商品信息
        $.ajax({
            //url: "http://" + ipAddress + ":8080/user/get_user_info",
            url: "http://" + ipAddress + ":8003/cart/cart/"+value,
            type: "GET",
            async: false,
            data: null,
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                console.log(" data=aaaaaaaaaaaa===  " + data.data.goodsVO);
                if (data.success===true) {
                        var eachTotal=data.data.goodsVO.goodsPrice * data.data.cart.number;
                        $("#J_goodsList").append("<li class=\"clearfix\">\n" +
                            "                            <div class=\"col col-img\">\n" +
                            "                                <img src='"+data.data.goodsVO.picture+"' width=\"30\" height=\"30\">\n" +
                            "                            </div>\n" +
                            "                            <div class=\"col col-name\">\n" +
                            "\n" +
                            "                                <a href='./goodsDetail.html?keywords="+data.data.goodsVO.goodsName+"' target=\"_blank\">\n" +
                            "                                    "+data.data.goodsVO.skuName+"                                   </a>\n" +
                            "                            </div>\n" +
                            "\n" +
                            "                            <div class=\"col col-price\">\n" +
                            "                                <span name='price' id='price"+index+"'>"+data.data.cart.price+"</span>元 x <span class='number' name='number' id='number"+index+"'>"+data.data.cart.number+"</span>                                    </div>\n" +
                            "                            <div class=\"col col-status\">\n" +
                            "                                &nbsp;\n" +
                            "                            </div>\n" +
                            "                            <div class=\"col col-total\">\n" +
                            "                                <span name='eachTotal' class='eachTotal' id='eachTotal"+index+"'>"+eachTotal+"</span>元\n" +
                            "                            </div>\n" +
                            "\n" +
                            "                        </li>");
                        console.log("value.goodsVO.goodsName:==="+data.data.goodsVO.goodsName);

                        var orderProductVO={
                            cartId:value,
                            spuId:data.data.cart.spuId,
                            skuId:data.data.cart.skuId,
                            goodsName:data.data.cart.goodsName,
                            goodsNumber:data.data.cart.number,
                            goodsPrice:data.data.cart.price
                            };
                        orderProductVOArray.push(orderProductVO);
                }else{
                    layer.msg("错误信息："+value.message)
                }
            },
            error: function () {
                layer.msg("后台服务器开小差了...")
            }
        })
    });
};

//选择收货地址
var confirmReceipt=function(obj){
    $(obj).css("border","1px solid red");
    $.each($(obj).siblings(),function (index,value) {
        $(value).css("border","1px solid grey");
    })
};


//得到订单信息
var checkInfo= function(obj){
    //商品件数，不是商品种类数
    var item_count=Number(0);
    var total_merchandise=Number(0);
    var transfer_fee=0;

    $(".number").each(function (i) {
        var id=$(this).attr("id");
        console.log("number==aaaaaaaaa==="+id);
        item_count+=Number($("#"+id).html());
    });

    $.each($("span[name='eachTotal']"),function (index,value) {
        total_merchandise+=Number($(value).html());
    });

    var duePay=total_merchandise + transfer_fee;

    console.log("item_count==="+item_count);
    console.log("transfer_fee==="+transfer_fee);
    console.log("total_merchandise==="+total_merchandise);
    console.log("duePay==="+duePay);

    $("#item_count").html(item_count);
    $("#duePay").html(duePay);
    $("#transfer_fee").html(transfer_fee);
    $("#total_merchandise").html(total_merchandise);

};

//下单
var placeOrder=function (obj) {
    var item_count=$("#item_count").html();
    var total_merchandise=$("#total_merchandise").html();
    var transfer_fee=$("#transfer_fee").html();
    var duePay=$("#duePay").html();
    var receiptId="";
    $.each($("div[name='receipt']"),function (index,value) {
        console.log("value==="+value);
        if ($(value).attr("style")==="border: 1px solid red;") {
            receiptId = $(value).attr("id");
            //alert("receiptId==="+receiptId);
        }
    });
    if (receiptId==""){
        layer.msg("请先选择收货地址!");
        return false;
    }


    var transfer_way="包邮";
    var remark=$("#remark").val();
    var orderInfo={
        receiptId:receiptId,
        itemCount:item_count,
        totalMerchandise:total_merchandise,
        transferWay:transfer_way,
        transferFee:transfer_fee,
        remark:remark
    };
    var cartIdArray=getUrlParms("cartIdList").split(',');

    var checkoutVO={
        orderProductVOArray:orderProductVOArray,
        orderInfo:orderInfo,
        cartIdArray:cartIdArray
    };

    console.log("checkoutVO======"+checkoutVO);

    console.log("remark5555555555555==="+remark);
    console.log("item_count5555555555555==="+item_count);
    console.log("transfer_fee55555555555555==="+transfer_fee);
    console.log("total_merchandise5555555555==="+total_merchandise);
    console.log("duePay55555555555==="+duePay);
    console.log("receiptId5555555555555==============="+receiptId);

    console.log("序列化后的checkoutVo=="+JSON.stringify(checkoutVO));

    $.ajax({
        url: "http://"+ipAddress+":8004/orderInfo/placeOrder",
        type: "POST",
        async: true,
        data: JSON.stringify(checkoutVO),
        contentType:"application/json",
        dataType: "json",
        success:function (data) {
            //console.log(" data cartVOList====  "+data.message);
            if (data.message==="下单成功！"&&data.success==true) {
                layer.msg(""+data.message+"两秒后跳转");
                setTimeout(function(){//两秒后跳转
                    window.location.href="./orderPay.html";
                },2000);
            }else{
                layer.msg(""+data.message+"两秒后跳转");
                setTimeout(function(){//两秒后跳转
                    window.location.href = "./cart.html";
                },2000);
            }

        },
        error:function () {
            layer.message("服务器开小差了!!!"+data.data.message);
        }
    });


}



//新增收货地址
var newReceipt=function(obj){
    //页面层
    layer.open({
        type: 2,
        title: '添加新收货地址',
        area: ['660px', '460px'],
        content: ['testNewReceipt.html', 'no']
    })
};


//修改收货地址
var updateReceipt=function(obj){
    //页面层
    layer.open({
        type: 2,
        title: '添加新收货地址',
        area: ['660px', '460px'],
        content: ['testNewReceipt.html', 'no']
    })
};